<script setup>
import { useUserStore } from '@/store/modules/user'
import { Message, Lock } from '@element-plus/icons-vue'
import SendMessageBtn from './SendMessageBtn.vue'
import ConfirmForm from './ConfirmForm.vue'
import { checkMail } from '@/api/user'
import { EMAIL_REGEXP } from '@/utils/regExp'

// 获取router变量
const vueRouter = useRouter()
// 获取store变量
const userStore = useUserStore()

const emailFormRef = ref()
const step = ref('one')

// 定义表单对象
const emailFormModel = reactive({
  email: '',
  code: '',
  loginButtonDisabled: false,
  loginButtonLoading: false,
  loginButtonName: '下一步'
})
// 定义表单校验规则
const emailFormRules = reactive({
  email: [
    { required: true, message: '请输入邮箱！', trigger: 'blur' },
    { pattern: EMAIL_REGEXP, trigger: 'blur', message: '请输入正确的邮箱' }
  ],
  code: [{ required: true, message: '请输入邮箱验证码！', trigger: 'blur' }]
})

const validate = () => {
  emailFormRef.value.validateField(['email'])
}

// 提交表单方法
const submitForm = () => {
  emailFormModel.loginButtonDisabled = true
  emailFormModel.loginButtonLoading = true
  emailFormRef.value.validate((valid) => {
    if (valid) {
      const param = { mail: emailFormModel.email, code: emailFormModel.code }
      checkMail(param).then((res) => {
        step.value = 'two'
      })
    } else {
      emailFormModel.loginButtonDisabled = false
      emailFormModel.loginButtonLoading = false
    }
  })
}
</script>

<template>
  <el-form v-if="step === 'one'" ref="emailFormRef" :model="emailFormModel" :rules="emailFormRules">
    <el-form-item prop="email">
      <el-input v-model="emailFormModel.email" :prefix-icon="Message" placeholder="请输入邮箱" clearable />
    </el-form-item>
    <el-form-item prop="code">
      <div class="flex flex-grow items-center">
        <el-input
          v-model="emailFormModel.code"
          type="code"
          :prefix-icon="Lock"
          placeholder="请输入邮箱验证码"
          clearable
        />
        <SendMessageBtn operation="FindByEmail" :userName="emailFormModel.email" @validate="validate" />
      </div>
    </el-form-item>
    <div class="flex justify-center mt-6">
      <el-button
        type="primary"
        @click="submitForm(emailFormRef)"
        :disabled="emailFormModel.loginButtonDisabled"
        :loading="emailFormModel.loginButtonLoading"
      >
        {{ emailFormModel.loginButtonName }}
      </el-button>
    </div>
  </el-form>
  <ConfirmForm v-else :phoneNum="emailFormModel.email" />
</template>

<style lang="scss" scoped></style>
